<template>
	<view class="page-container">
		<view class="form-container">
			<view class="title">用户注册</view>

			<view class="input-group">
				<input type="text" v-model="username" placeholder="请设置用户名" class="input" :disabled="isLoading" />
				<text class="error-text" v-if="errors.username">{{ errors.username }}</text>
			</view>

			<view class="input-group">
				<input type="password" v-model="password" placeholder="请设置密码（至少6位）" class="input"
					:disabled="isLoading" />
				<text class="error-text" v-if="errors.password">{{ errors.password }}</text>
			</view>

			<view class="input-group">
				<input type="password" v-model="confirmPwd" placeholder="请确认密码" class="input" :disabled="isLoading" />
				<text class="error-text" v-if="errors.confirmPwd">{{ errors.confirmPwd }}</text>
			</view>

			<button class="btn register-btn" @click="handleRegister" :disabled="isLoading">
				<template v-if="isLoading">
					<text class="loading">注册中...</text>
				</template>
				<template v-else>
					<text>注册</text>
				</template>
			</button>

			<view class="link-container">
				<text>已有账号？</text>
				<text class="link" @click="goToLogin">立即登录</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				username: '',
				password: '',
				confirmPwd: '',
				isLoading: false,
				errors: {
					username: '',
					password: '',
					confirmPwd: ''
				},
				// 云数据库引用
				db: null
			};
		},
		onLoad() {
			// 初始化云数据库（适配uni-app各平台云开发）
			this.initCloudDB();
		},
		methods: {
			// 初始化云数据库
			initCloudDB() {
				try {
					// 1. 微信小程序云开发
					//#ifdef MP-WEIXIN
					if (!wx.cloud) {
						uni.showToast({
							title: '请先开通微信云开发',
							icon: 'none'
						});
						return;
					}
					wx.cloud.init({
						env: '你的微信云环境ID' // 替换为你的微信云环境ID
					});
					this.db = wx.cloud.database();
					//#endif

					// 2. uniCloud（阿里云/腾讯云）
					//#ifdef APP-PLUS || H5 || MP-ALIPAY || MP-BAIDU
					this.db = uniCloud.database();
					//#endif

					console.log('云数据库初始化成功');
				} catch (err) {
					console.error('云数据库初始化失败：', err);
					uni.showToast({
						title: '数据库初始化失败',
						icon: 'none'
					});
				}
			},

			// 跳转到登录页
			goToLogin() {
				uni.reLaunch({
					url: '/pages/components/login/login',
					fail: () => {
						uni.reLaunch({
							url: '/pages/components/login/login'
						});
					}
				});
			},

			// 清空错误提示
			clearError(field) {
				this.errors[field] = '';
			},

			// 表单验证
			async validateForm() {
				let isValid = true;
				this.errors = {
					username: '',
					password: '',
					confirmPwd: ''
				};

				// 用户名验证
				if (!this.username.trim()) {
					this.errors.username = '请输入用户名';
					isValid = false;
				} else {
					// 云数据库查询用户名是否已存在
					try {
						const userRes = await this.db.collection('users').where({
							username: this.username.trim()
						}).get();

						if (userRes.data && userRes.data.length > 0) {
							this.errors.username = '该用户名已被注册';
							isValid = false;
						}
					} catch (err) {
						console.error('查询用户名失败：', err);
						this.errors.username = '验证用户名失败，请重试';
						isValid = false;
					}
				}

				// 密码验证
				if (this.password.length < 6) {
					this.errors.password = '密码至少6位';
					isValid = false;
				}

				// 确认密码验证
				if (this.password !== this.confirmPwd) {
					this.errors.confirmPwd = '两次密码不一致';
					isValid = false;
				}

				return isValid;
			},

			// 处理注册逻辑
			async handleRegister() {
				// 验证表单
				const isValid = await this.validateForm();
				if (!isValid) return;

				// 检查数据库是否初始化
				if (!this.db) {
					uni.showToast({
						title: '数据库未初始化',
						icon: 'none'
					});
					return;
				}

				this.isLoading = true;
				try {
					// 模拟接口请求延迟
					await this.mockRegister();

					// 插入用户数据到云数据库
					const addRes = await this.db.collection('users').add({
						username: this.username.trim(),
						password: this.password, // 注意：生产环境需加密存储密码
						createTime: new Date(),
						lastLoginTime: null,
						status: 1 // 1-正常 0-禁用
					});

					if (addRes._id || addRes.id) {
						uni.showToast({
							title: '注册成功，即将跳转到登录页',
							icon: 'none',
							duration: 1500
						});
						setTimeout(() => {
							this.goToLogin();
						}, 1500);
					} else {
						throw new Error('注册失败，未返回ID');
					}
				} catch (err) {
					uni.showToast({
						title: err.message || '注册失败，请重试',
						icon: 'none'
					});
					console.error('注册错误：', err);
				} finally {
					this.isLoading = false;
				}
			},

			// 模拟注册请求延迟
			mockRegister() {
				return new Promise((resolve) => {
					setTimeout(resolve, 1500);
				});
			}
		}
	};
</script>

<style scoped>
	.page-container {
		display: flex;
		justify-content: center;
		padding: 40rpx 30rpx;
		background-color: #f9f9f9;
		min-height: 100vh;
		box-sizing: border-box;
	}

	.form-container {
		width: 100%;
		max-width: 500rpx;
		background-color: #fff;
		padding: 60rpx 40rpx;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
	}

	.title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		text-align: center;
		margin-bottom: 60rpx;
	}

	.input-group {
		margin-bottom: 30rpx;
	}

	.input {
		width: 100%;
		height: 90rpx;
		padding: 0 20rpx;
		border: 2rpx solid #eee;
		border-radius: 8rpx;
		font-size: 28rpx;
		box-sizing: border-box;
	}

	.input:focus {
		border-color: #007aff;
		outline: none;
	}

	.error-text {
		display: block;
		color: #f53f3f;
		font-size: 24rpx;
		margin-top: 10rpx;
		line-height: 1.4;
	}

	.btn {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		font-size: 30rpx;
		border-radius: 8rpx;
		margin-bottom: 30rpx;
	}

	.register-btn {
		background-color: #007aff;
		color: #fff;
	}

	.loading {
		display: inline-flex;
		align-items: center;
	}

	.loading::before {
		content: '';
		width: 16px;
		height: 16px;
		border: 2px solid rgba(255, 255, 255, 0.5);
		border-radius: 50%;
		border-top-color: #fff;
		animation: spin 1s linear infinite;
		margin-right: 6px;
	}

	@keyframes spin {
		to {
			transform: rotate(360deg);
		}
	}

	.link-container {
		text-align: center;
		font-size: 26rpx;
		color: #666;
	}

	.link {
		color: #007aff;
		margin-left: 10rpx;
		text-decoration: underline;
		cursor: pointer;
		user-select: none;
	}
</style>